<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\OrdersModel;
use Illuminate\Support\Facades\DB;

class OrdersDao extends BaseDao
{

    public static function builder_query($params = [],$orderBy = 'DESC'): \Illuminate\Database\Eloquent\Builder
    {
        $query = OrdersModel::query();

        $query->when(checkIsHasField($params,'u_order_id'),function ($query)use ($params){
            $query->where('u_order_id',$params['u_order_id']);
        });

        $query->when(checkIsHasField($params,'u_status'),function ($query)use ($params){
            $query->where('u_status',$params['u_status']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });




        return $query->orderBy('created_at',$orderBy);
    }

    /**
     * @throws SysExceptions
     */
    public static function create_order($params = []){
        checkForData(['u_price'],['请选择或者输入单子数量'],$params);
        $userInfo = UsersDao::builder_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        //一天最多下20单
        $beginTime = strtotime(date('Y-m-d'));
        $cPriceAll = self::builder_query([
            'user_id'=>$params['user_id']
        ])->where('created_at','>',$beginTime)->count();
        //每日最多单数

        //检测账户是否激活
        if($userInfo['is_activity'] != 1){
            self::error('用户未激活');
        }
        //扣除usdt
        if($userInfo['u_price'] < $params['u_price']){
            self::error('金额不足');
        }
        $settingsDan = 50;
        if($cPriceAll+1 > 20){
            self::error('一天最多下20单');
        }
        //下单
        DB::beginTransaction();
        try {
            $goodsItem = '';
            $goods = CommonDao::goods();
            foreach ($goods as $value){
                if($value['u_price'] == $params['u_price']){
                    $goodsItem = $value;
                }
            }
            //扣除金额
            BillsDao::moneyUpdate(-$params['u_price'],$params['user_id'],'用户购买单子');
            //创建订单
                self::builder_query()->create([
                    'json_data'=>json_encode($goodsItem,JSON_UNESCAPED_UNICODE),
                    'u_price'=>$params['u_price'],
                    'u_day_over'=>(strtotime(date('Y-m-d'))+864000),
                    'u_rate'=>0.04,
                    'user_id'=>$params['user_id'],
                    'u_status'=>0,
                    'u_over_rate_price'=>bcmul($params['u_price'],1.04,2)
                ]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    //获取订单信息
    public static function orders(array $params)
    {
        return self::builder_query($params)->get();
    }






    //奖励星级奖励
    public static function changeLevelData($userId,$price = 0)
    {
        //查询上级以上可以根据ID来进行排序，正常邀请顺序是从上到下
        //查询一星

        $now_level= 10;

        $dataSettings = [
            10=>0.2,
            20=>0.4,
            30=>0.6,
            40=>0.8,
            50=>1.0
        ];
        while(true){
            if($now_level > 50){
                break;
            }
            $user_star = UsersDao::builder_query()->where('spread_ids','LIKE','%,'.$userId.',%')->where('user_level',$now_level)->orderBy('user_id','DESC');
            if($user_star->exists()){
                $user_star = $user_star->first()->toArray();
                $moneyNow = $dataSettings[$now_level];
                //奖励给这个人
                BillsDao::moneyUpdate($moneyNow,$user_star['user_id'],'团队流水奖励');
            }
            $now_level += 10;
        }
    }

    public static function orderRecive()
    {
        //小于当天时间的5分钟的
        $beginTime = strtotime(date('Y-m-d'));
        $ordersLists = self::builder_query([],'ASC')->where('u_status',0)->where('u_day_over','<=',$beginTime);
        if($ordersLists->exists()){
            $orderInfo = $ordersLists->first()->toArray();
            //发放奖励
            DB::beginTransaction();
            try {
                //发放实际奖励
                BillsDao::moneyUpdate($orderInfo['u_over_rate_price'],$orderInfo['user_id'],'发放实际奖励');
                self::builder_query([
                    'u_order_id'=>$orderInfo['u_order_id']
                ])->update([
                    'u_err_msg'=>'success',
                    'u_status'=>1
                ]);
                //奖励别的比如团队的流水奖励
                self::changeLevelData($orderInfo['user_id'],150);
                DB::commit();
            }catch (\Exception $exception){
                DB::rollBack();
                //失败和失败原因
                self::builder_query([
                    'u_order_id'=>$orderInfo['u_order_id']
                ])->update([
                    'u_err_msg'=>$exception->getMessage(),
                    'u_status'=>2
                ]);
            }
        }
    }

    //自动匹配订单
    public static function order_auto_order()
    {
        $user_auto_u_price = UsersDao::builder_query()->where('auto_u_price', '>', 0)->orderByDesc('user_id');
        if ($user_auto_u_price->exists()) {
            $user_auto_u_price = $user_auto_u_price->first()->toArray();
            $autoMoneys = 0;
            $moneys = [49.8, 98.3, 196.5, 485.6, 985.2];
            foreach ($moneys as $value) {
                if ($user_auto_u_price['auto_u_price'] > $value) {
                    $autoMoneys = $value;
                }
            }
            //获取今天已经下的单数
            $beginTime = strtotime(date('Y-m-d'));
            $cPriceAll = self::builder_query([
                'user_id' => $user_auto_u_price['user_id']
            ])->where('created_at', '>=', $beginTime)->count();
            $sheng = 20 - $cPriceAll;
            //等于0
            if ($sheng == 0) {
                //并且将钱返还
                DB::beginTransaction();
                try {
                    UsersDao::builder_query(['user_id' => $user_auto_u_price['user_id']])->update([
                        'auto_u_price' => 0
                    ]);
                    BillsDao::moneyUpdate($user_auto_u_price['auto_u_price'], $user_auto_u_price['user_id'], '自动托管部分退回');
                    DB::commit();
                } catch (\Exception $exception) {
                    DB::rollBack();
                }
                return;
            }
            DB::beginTransaction();
            try {
                $goodsItem = '';
                $goods = CommonDao::goods();
                foreach ($goods as $value) {
                    if ($value['u_price'] == $autoMoneys) {
                        $goodsItem = $value;
                    }
                }
                //扣除金额
                //创建订单
                if($autoMoneys > 0) {
                    self::builder_query()->create([
                        'json_data' => json_encode($goodsItem, JSON_UNESCAPED_UNICODE),
                        'u_price' => $autoMoneys,
                        'u_day_over' => (strtotime(date('Y-m-d')) + 864000),
                        'u_rate' => 0.04,
                        'user_id' => $user_auto_u_price['user_id'],
                        'u_status' => 0,
                        'u_over_rate_price' => bcmul($autoMoneys, 1.04, 2)
                    ]);
                }
                //将剩下的进行扣除并且多余的进行返还
                $shengMoneys = bcsub($user_auto_u_price['auto_u_price'], $autoMoneys, 2);
                //将钱返还
                if ($shengMoneys > 0) {
                    BillsDao::moneyUpdate($shengMoneys, $user_auto_u_price['user_id'], '自动托管部分退回');
                }
                UsersDao::builder_query(['user_id' => $user_auto_u_price['user_id']])->update([
                    'auto_u_price' => 0
                ]);
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
                self::error($exception->getMessage());
            }
        }
    }

    public static function pageOrders(array $all)
    {
        return self::builder_query($all)->paginate();
    }

    public static function count()
    {
        return [
            'countAll'=>self::builder_query()->count(),
            'countDai'=>self::builder_query(['u_status'=>0])->count(),
            'countFan'=>self::builder_query(['u_status'=>1])->count()
        ];
    }
}
